use std::{io, thread};
use std::net::UdpSocket;
use std::time::Duration;

fn main() -> io::Result<()> {
    // 从给定的地址创建一个 UDP 套接字。
    let socket = UdpSocket::bind("127.0.0.1:3400").expect("couldn't bind to address");
    socket.connect("127.0.0.1:7788").expect("connect function failed");

    // 返回创建此套接字的套接字地址。
    println!("{:?}", socket.local_addr());
    // 返回此套接字的远程地址。
    println!("{:?}", socket.peer_addr());

    loop {
        let msg = String::from("hello world");
        socket.send(msg.as_bytes()).expect("send failed");
        println!("sent: {}", msg);

        thread::sleep(Duration::from_secs(1));

        let mut buf = [0; 1024];
        let (n, addr) = socket.recv_from(&mut buf).expect("recv_from failed");
        println!("received {} bytes from {}", n, addr);
        socket.send_to(&buf[..n], addr).expect("send_to failed");
    }
}

